The previous example made use of early binding to print out the vehicle description data for the Winnebago type. This was possible due to the fact that the VehicleDescriptionAttribute class type was defined as a public member in the AttributedCarLibrary assembly. It is also possible to make use of dynamic loading and late binding to reflect over attributes.
Create a new project called VehicleDescriptionAttributeReaderLateBinding and copy AttributedCarLibrary.dll to the project’s \bin\Debug directory. Now, update your Program class as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace VehicleDescriptionAttributeReaderLateBinding { class Program { static void Main(string[] args) { Console.WriteLine("***** Value of VehicleDescriptionAttribute *****\n"); ReflectAttributesUsingLateBinding(); Console.ReadLine(); } private static void ReflectAttributesUsingLateBinding() { try { // Load the local copy of AttributedCarLibrary. Assembly asm = Assembly.Load("AttributedCarLibrary"); // Get type info of VehicleDescriptionAttribute. Type vehicleDesc = asm.GetType("AttributedCarLibrary.VehicleDescriptionAttribute"); // Get type info of the Description property. PropertyInfo propDesc = vehicleDesc.GetProperty("Description"); // Get all types in the assembly. Type[] types = asm.GetTypes(); // Iterate over each type and obtain any VehicleDescriptionAttributes. foreach (Type t in types) { object[] objs = t.GetCustomAttributes(vehicleDesc, false); // Iterate over each VehicleDescriptionAttribute and print // the description using late binding. foreach (object o in objs) { Console.WriteLine("-> {0}: {1}\n", t.Name, propDesc.GetValue(o, null)); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
If you were able to follow along with the examples in this chapter, this code should be (more or less) self-explanatory. The only point of interest is the use of the PropertyInfo.GetValue() method, which is used to trigger the property’s accessor. Here is the output of the current example:
***** Value of VehicleDescriptionAttribute ***** -> Motorcycle: My rocking Harley -> HorseAndBuggy: The old gray mare, she ain't what she used to be... -> Winnebago: A very long, slow, but feature-rich auto
Source Code The VehicleDescriptionAttributeReaderLateBinding project is included under the Chapter 15 subdirectory.